package com.dog.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * Author: Dmitriy Akishin
 * Date: 10.02.2009
 * Time: 13:53:31
 */
public class SpringManager implements ApplicationContextAware {
    private static ApplicationContext SPRING_CONTEXT;


    public static Object getBean(String beanName) {
        return !isApplicationContextSet()? null : SPRING_CONTEXT.getBean(beanName);
    }


    public static <T> T getBean(Class<T> clazz) {
        Map<String, Object> beans = (Map<String, Object>) SPRING_CONTEXT.getBeansOfType(clazz);
        if (beans.size() > 1) {
            throw new RuntimeException("More than one beans found in context with class " + clazz);
        }
        if (beans.size() == 0) {
            throw new RuntimeException("Bean with class " + clazz + " not found");
        }
        return (T) beans.entrySet().iterator().next().getValue();
    }


    public void setApplicationContext(ApplicationContext applicationContext) {
        SPRING_CONTEXT = applicationContext;
    }

    private static boolean isApplicationContextSet() {
        return SPRING_CONTEXT != null;
    }


}
